package com.kk.feign.controller;

import com.kk.feign.service.PaymentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author o_o
 * @date 2022-08-04
 */
@RestController
//@DefaultProperties(defaultFallback = "globalFallbackMethod")
public class FeignController {

    @Autowired
    private PaymentService paymentService;

    /**
     * =============服务降级==================
     */
    @GetMapping("/order/payment/feign")
    @HystrixCommand(fallbackMethod = "pocketBottom", commandProperties = {
            @HystrixProperty(name = HystrixPropertiesManager.EXECUTION_ISOLATION_THREAD_TIMEOUT_IN_MILLISECONDS, value = "3000")
    })
    public String feign() {
//        try {
//            TimeUnit.SECONDS.sleep(4);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        return paymentService.feign();
    }

    @GetMapping("/order/feign")
    @HystrixCommand
    public String feign2() {
//        try {
//            TimeUnit.SECONDS.sleep(4);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        return paymentService.feign();
    }

    public String pocketBottom() {
        return "客户端超时或报错了，调用爹来兜底！";
    }

    public String globalFallbackMethod() {
        return "全局默认的服务降级，请稍后再试！";
    }

    /**
     * =============服务熔断==================
     */
    @HystrixCommand(fallbackMethod = "hystrixCircuitBreakerFallback", commandProperties = {
            //是否开启断路器
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ENABLED, value = "true"),
            //请求次数
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD, value = "10"),
            //时间窗口期
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, value = "10000"),
            //失败率到达多少跳闸
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE, value = "60"),
    })
    @GetMapping("/feign/circuitBreak")
    public String hystrixCircuitBreaker(int id) {
        if (id < 0) {
            throw new RuntimeException("run error.");
        }
        return "OK";
    }

    public String hystrixCircuitBreakerFallback(int id) {
        return "break";
    }

    @GetMapping("/zipkin")
    public String zipkin(){
        return paymentService.zipkin();
    }
}
